package com.tang.thepath.view;

import android.content.Context;
import android.util.AttributeSet;
import android.webkit.WebResourceRequest;
import android.webkit.WebResourceResponse;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

public class MyWebView extends WebView{

    private WebViewClient webViewClient = new WebViewClient(){
        @Override
        public WebResourceResponse shouldInterceptRequest(WebView view, final WebResourceRequest request) {
            String url = request.getUrl().toString();
            return getNewResponse(url,request.getMethod());
        }

    };

    private WebResourceResponse getNewResponse(String url,String method) {

        try {
            OkHttpClient httpClient = new OkHttpClient();

            Request request = new Request.Builder()
                    .url(url.trim())
                    .addHeader("Authorization", "Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpc3MiOiJodHRwOlwvXC9oYm1hcGkxLmp5cTM2NS5jb206MjIzMyIsImF1ZCI6InRva2VuX3VzZXIiLCJpYXQiOjE1MDc0MjQ5NjIsImV4cCI6MTUwNzUxMTM2MiwidW5pcWlkIjoiNTlkOTdhYzI2M2VhMSIsImxvZ2luX2luZm8iOnsidXNlcl9yb2xlX2lkIjoiNCJ9fQ.6uf4KTMMQtYlAfsveUKxJvQPX150FQbDTxU-JxKpFTA") // Example header
                    .build();

            Response response = null;
            if(method.equalsIgnoreCase("GET")){
                response = httpClient.newCall(request).execute();
            }else if(method.equalsIgnoreCase("POST")){
                response = httpClient.newCall(request).execute();

            }


            return new WebResourceResponse(
                    null,
                    response.header("content-encoding", "utf-8"),
                    response.body().byteStream()
            );

        } catch (Exception e) {
            return null;
        }

    }

    public MyWebView(Context context) {
        super(context);
        this.setWebViewClient(webViewClient);
    }

    public MyWebView(Context context, AttributeSet attrs) {
        super(context, attrs);
        this.setWebViewClient(webViewClient);
    }


}
